
import axios from 'axios'

const url = '/webArticles'

export function submitArticle (title, author, tag, fileId, content, token) {
  const data = {
    title,
    author,
    tag,
    fileId,
    content
  }

  return axios({
    method: 'POST',
    url,
    headers: {
      Authorization: `Bearer ${token}\n`
    },
    data
  }).then((res) => {
    return Promise.resolve(res.data)
  }).catch((err) => {
    return Promise.reject(err)
  })
}

export function getList (limit, offset, token) {
  return axios({
    method: 'GET',
    url,
    headers: {
      Authorization: `Bearer ${token}\n`
    },
    params: {
      limit,
      offset,
      sort: {
        id: -1
      }
    }
  }).then((res) => {
    return Promise.resolve(res.data)
  }).catch((err) => {
    return Promise.reject(err)
  })
}

export function getTotalCount (fields, token) {
  return axios({
    method: 'GET',
    url,
    headers: {
      Authorization: `Bearer ${token}\n`
    },
    params: {
      fields
    }

  }).then((res) => {
    return Promise.resolve(res.data)
  }).catch((err) => {
    return Promise.reject(err)
  })
}

export function delList (id, token) {
  return axios({
    method: 'DELETE',
    url: `${url}/${id}`,
    headers: {
      Authorization: `Bearer ${token}\n`
    }
  }).then((res) => {
    return Promise.resolve(res.data)
  }).catch((err) => {
    return Promise.reject(err)
  })
}

export function getDetail (id, token) {
  return axios({
    method: 'GET',
    url: `${url}/${id}`
    // headers: {
    //   Authorization: `Bearer ${token}\n`
    // }
  }).then((res) => {
    return Promise.resolve(res.data)
  }).catch((err) => {
    return Promise.reject(err)
  })
}

export function updateDeatil (id, title, author, readingAmount, region, fileId, content, token) {
  return axios({
    method: 'PUT',
    url: `${url}/${id}`,
    headers: {
      'Authorization': `Bearer ${token}\n`
    },
    data: {
      title,
      author,
      region,
      fileId,
      content,
      readingAmount
    }
  }).then((res) => {
    return Promise.resolve(res.data)
  }).catch((err) => {
    return Promise.reject(err)
  })
}

export function getGroupData (tag) {
  return axios({
    method: 'GET',
    url,
    params: {
      having: {
        tag
      },
      sort: {
        id: -1
      }
    }
  }).then((res) => {
    return Promise.resolve(res.data)
  }).catch((err) => {
    return Promise.reject(err)
  })
}

export function getPageGroupData (tag, offset) {
  return axios({
    method: 'GET',
    url,
    params: {
      having: {
        tag
      },
      sort: {
        id: -1
      },
      offset,
      limit: 10
    }
  }).then((res) => {
    return Promise.resolve(res.data)
  }).catch((err) => {
    return Promise.reject(err)
  })
}
